using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
using System;

public class BaseAIPathEnemy : MonoBehaviour
{
    public Transform target;
    public float speed = 200f;
    public float nexWaypointDistance = 3f;
    public bool CanFly;

    protected Path path;
    protected int currentWaypoiont = 0;
    protected bool reachedEndOfPath = false;
    protected bool FindPlayer = false;
    

    protected Seeker seeker;
    protected Rigidbody2D rb;

    protected void Awake()
    {
        MsgSignal.AddListener<(bool, GameObject)>(EventConst.Brid, GoFindPlayer);
    }

    protected virtual void GoFindPlayer((bool,GameObject) enemy)
    {
        if (this.gameObject == enemy.Item2)
            FindPlayer = enemy.Item1;
    }

    protected virtual void Start()
    {
        seeker = GetComponent<Seeker>();
        rb = GetComponent<Rigidbody2D>();
        InvokeRepeating("UpdatePath", 0f, .4f);
        if (CanFly)
        {
            rb.gravityScale = 0;
        }
        else
            rb.gravityScale = 1;
    }

    protected virtual void UpdatePath()
    {
        if(seeker.IsDone())
            seeker.StartPath(rb.position, target.position, OnPathComplete);
    }

    protected void OnPathComplete(Path p)
    {
        if (!p.error)
        {
            path = p;
            currentWaypoiont = 0;
        }
    }

    protected virtual void Update()
    {
        if (FindPlayer)
        {
            FindPlayerAndGo();
        }
        else
        {
            NotFindPlayer();
        }
    }

    protected virtual void FindPlayerAndGo()
    {
        if (path == null)
            return;
        if (currentWaypoiont >= path.vectorPath.Count)
        {
            reachedEndOfPath = true;
            return;
        }
        else
        {
            reachedEndOfPath = false;
        }
        Vector2 dirction = ((Vector2)path.vectorPath[currentWaypoiont] - rb.position).normalized;
        Vector2 force = dirction * speed * Time.deltaTime;
        rb.AddForce(force);
        float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoiont]);
        if (distance < nexWaypointDistance)
        {
            currentWaypoiont++;
        }

        if (force.x< 0)
        {
            transform.localScale = new Vector3(-1f, 1f, 1f);
        }
        else if (force.x > 0)
        {
            transform.localScale = new Vector3(1f, 1f, 1f);
        }
    }

    protected virtual void NotFindPlayer()
    {
        
    }

    private void OnDestroy()
    {
        MsgSignal.RemoveListener<(bool, GameObject)>(EventConst.Brid, GoFindPlayer);
    }
}
